#include "spi.h"

void SPI_Init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;

    GPIOA->CRL |= GPIO_CRL_MODE4;
    GPIOA->CRL &= ~GPIO_CRL_CNF4;

    GPIOA->CRL |= GPIO_CRL_MODE5;
    GPIOA->CRL |= GPIO_CRL_CNF5_1;
    GPIOA->CRL &= ~GPIO_CRL_CNF5_0;

    GPIOA->CRL |= GPIO_CRL_MODE7;
    GPIOA->CRL |= GPIO_CRL_CNF7_1;
    GPIOA->CRL &= ~GPIO_CRL_CNF7_0;

    GPIOA->CRL &= ~GPIO_CRL_MODE6;
    GPIOA->CRL &= ~GPIO_CRL_CNF6_1;
    GPIOA->CRL |= GPIO_CRL_CNF6_0;

    SPI1->CR1 |= SPI_CR1_MSTR;

    SPI1->CR1 |= SPI_CR1_SSM;
    SPI1->CR1 |= SPI_CR1_SSI;

    SPI1->CR1 &= ~SPI_CR1_CPOL;
    SPI1->CR1 &= ~SPI_CR1_CPHA;

    SPI1->CR1 &= ~SPI_CR1_BR;
    SPI1->CR1 |= SPI_CR1_BR_0;

    SPI1->CR1 &= ~SPI_CR1_DFF;

    SPI1->CR1 &= ~SPI_CR1_LSBFIRST;

    SPI1->CR1 |= SPI_CR1_SPE;
}

uint8_t SPI_SwapByte(uint8_t byte)
{
    while ((SPI1->SR & SPI_SR_TXE) == 0)
    {}

    SPI1->DR = byte;

    while ((SPI1->SR & SPI_SR_RXNE) == 0)
    {}

    return (uint8_t)(SPI1->DR & 0xff);
    
}

